from flask import Blueprint, session, render_template, redirect, url_for, make_response, request

from models.user import User

main = Blueprint('index', __name__)


def current_user():
    uid = session.get('user_id', -1)
    u = User.find(uid)
    return u


@main.route("/")
def index():
    u = current_user()
    template = render_template("index.html", user=u)
    # 如果想要写入cookie，必须使用make_response函数
    # 然后再用set_cookie来设置cookie
    r = make_response(template)
    r.set_cookie('cookie_name', 'juran')
    return r


@main.route("/register", methods=['POST'])
def register():
    form = request.form
    u = User.register(form)
    return redirect(url_for('.index'))


@main.route("/login", methods=['POST'])
def login():
    form = request.form
    u = User.validate_login(form)
    if u is None:
        return redirect(url_for('.index'))
    else:
        session['user_id'] = u.id
        return redirect(url_for('.profile'))


@main.route('/profile')
def profile():
    u = current_user()
    if u is None:
        return redirect(url_for('.index'))
    else:
        return render_template('profile.html', user=u)


@main.route("/logout", methods=['get'])
def log_out():
    u = current_user()
    if u is None:
        return redirect(url_for('.index'))
    else:
        session.pop("user_id")
        return redirect(url_for(".index"))
